<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    //判断浏览器是否支持websocket
    if (window.WebSocket) {
        //创建WebSocket并且指定访问地址
        socket = new WebSocket("ws://localhost:7000/hello");
        //相当于channelRead0方法，ev对象会接收服务器端会送的消息，类似于ajax中的回电函数
        socket.onmessage = function (ev) {
            var responseText = document.getElementById("responseText");
            responseText.value = responseText.value + "\n" + ev.data;
        };
        //相当于连接开启，感知连接开启
        socket.onopen = function (ev) {
            var responseText = document.getElementById("responseText");
            responseText.value = responseText.value + "\n" + "连接开启...";
        };
        //相当于连接关闭，感知连接关闭
        socket.onclose = function (ev) {
            var responseText = document.getElementById("responseText");
            responseText.value = responseText.value + "\n" + "连接关闭...";
        };
    } else {
        alert("当前浏览器不支持websocket");
    }

    function send(message) {
        if (!window.socket) {
            //判断socket是否创建好，如果没有创建好，直接返回
            return;
        }
        //判断websocket是否处于open状态
        if (socket.readyState == WebSocket.OPEN) {
            //使用socket发送消息
            socket.send(message);
        }
    }
</script>
<form onsubmit="return false">
    <textarea name="message" style="height: 300px;width: 300px;"></textarea>
    <input type="button" value="发送消息" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="height: 300px;width: 300px;"></textarea>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>